#!/usr/bin/env node
const path = require('path');
const { program } = require('commander');
const { execSync } = require('child_process');
const fs = require('fs');
const { copyFiles } = require('./copy');

const staticPath = path.resolve(path.join(__dirname, '../static'));
const templatePath = path.resolve(path.join(__dirname, '../template'));

program
  .option('-m, --model <model-path>', '模型目录')
  .option('-o, --output <output-path>', '输出目录, 默认输出: 模板目录/out')
  .option('--app [app-code-name]', '发布模式改为应用, 模型目录将识别为应用')
  .option('--local-mode', '是否为本地模式', false)
  .parse(process.argv);

const { model, output, app, localMode } = program.opts();

const modelPath = path.resolve(model);
const outputPath = path.resolve(output);

// 本地模式不拷贝静态资源和调整git忽略文件，仅基于模型发布代码
if (!localMode) {
  copyFiles(staticPath, outputPath);
  console.log(`拷贝静态资源成功，静态资源路径：${staticPath}，输出路径：${outputPath}`);

  fs.renameSync(
    path.join(outputPath, '.gitignore.bak'),
    path.join(outputPath, '.gitignore'),
  );
}

const binPath = path.resolve(path.join(__dirname, '../node_modules/.bin'));

execSync(
  `${binPath}/ibizlab pub -m ${modelPath} -t ${templatePath} -o ${outputPath}/src/publish --app ${app} && ${binPath}/prettier --ignore-path "" "${outputPath}/src/publish/**/*.(ts|vue|tsx)" -w`,
);
copyFiles(`${outputPath}/src/publish/app`, `${outputPath}/public/static/app`);
fs.rmSync(`${outputPath}/src/publish/app`, { recursive: true, force: true }); // 递归删除目录及其内容

console.log(`发布模板成功，模型路径：${modelPath}，发布应用代码标识：${app}，模板路径：${templatePath}，输出路径：${outputPath}/src/publish`);